package com.app.medicalcontrol.fragment.User.child;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.app.medicalcontrol.R;
import com.app.medicalcontrol.basis.BasisApp;
import com.app.medicalcontrol.basis.BasisFragment;
import com.app.medicalcontrol.basis.Constants;
import com.app.medicalcontrol.bean.LoginBean;
import com.app.medicalcontrol.bean.UserBean;
import com.loopj.android.http.RequestParams;
import com.makeramen.roundedimageview.RoundedImageView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import my.http.HttpRestClient;
import my.http.MyHttpListener;

/**
 * Created by otis on 2018/4/11.
 */

public class UserCenterFragment extends BasisFragment implements RadioGroup.OnCheckedChangeListener{


    private RadioGroup mRadioGroup;
    private FrameLayout mLayout;

    private FragmentManager fragmentManager;
    private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW";
    private Fragment currentFragment = new Fragment();
    private List<Fragment> fragments = new ArrayList<>();
    private int currentIndex = 0;

    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.img_head)
    RoundedImageView headIcon;

    public static UserBean userBean;


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_user_center);

        mRadioGroup= (RadioGroup) findViewById(R.id.rg_radio_navigation);
        mRadioGroup.setOnCheckedChangeListener(this);
        userBean = UserBean.getInstance();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        fragmentManager =getChildFragmentManager();

        getUserInfo(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(CURRENT_FRAGMENT,currentIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.rb_first:
                currentIndex = 0;
                break;
            case R.id.rb_second:
                currentIndex = 1;
                break;
            case R.id.rb_third:
                currentIndex = 2;
                break;
        }
        showFragment();
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment(){
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //如果之前没有添加过
        if(!fragments.get(currentIndex).isAdded()){
            int a = currentIndex;
            transaction
                    .hide(currentFragment)
                    .add(R.id.fl_radio_show,fragments.get(currentIndex),""+currentIndex);  //第三个参数为添加当前的fragment时绑定一个tag
        }else{
            transaction
                    .hide(currentFragment)
                    .show(fragments.get(currentIndex));
        }
        currentFragment = fragments.get(currentIndex);
        transaction.commit();
    }

    /**
     * 恢复fragment
     */
    private void restoreFragment(){
        FragmentTransaction mBeginTreansaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            if(i == currentIndex){
                mBeginTreansaction.show(fragments.get(i));
            }else{
                mBeginTreansaction.hide(fragments.get(i));
            }
        }
        mBeginTreansaction.commit();
        //把当前显示的fragment记录下来
        currentFragment = fragments.get(currentIndex);
    }

    private void getUserInfo(final Bundle savedInstanceState) {

        showProgress();
        LoginBean.refreshToken(new LoginBean.Token_Listener() {
            @Override
            public void onSuccess() {

                RequestParams params = new RequestParams();
                params.put("ctoken", LoginBean.getInstance().getToken().getValue());
                HttpRestClient.get(Constants.URL_USER_INFO, params, new MyHttpListener() {
                            @Override
                            public void onSuccess(int httpWhat, Object result) {
                                userBean = (UserBean) result;
                                mTvUserName.setText(""+userBean.getNickname());
                                BasisApp.loadImg(mContext,userBean.getHead(),headIcon,R.mipmap.user_icon_default);
                            }

                            @Override
                            public void onFinish(int httpWhat) {
                                dismissProgress();
                                initFragment(savedInstanceState);
                            }
                        },
                        0, UserBean.class);
            }

            @Override
            public void onFailure() {

            }

            @Override
            public void onFinish() {

            }
        });

    }

    public void initFragment(Bundle savedInstanceState){
        if (savedInstanceState != null) { // “内存重启”时调用
            //获取“内存重启”时保存的索引下标
            currentIndex = savedInstanceState.getInt(CURRENT_FRAGMENT,0);
            //注意，添加顺序要跟下面添加的顺序一样！！！！
            fragments.removeAll(fragments);
            fragments.add(fragmentManager.findFragmentByTag(0+""));
            fragments.add(fragmentManager.findFragmentByTag(1+""));
            fragments.add(fragmentManager.findFragmentByTag(2+""));
            //恢复fragment页面
            restoreFragment();
        }else{      //正常启动时调用
            fragments.add(new UserInfoFragment());
            fragments.add(new ResetPwdFragment());
            fragments.add(new SettingFragment());
            showFragment();
        }
    }

}
